#include "I_BaseLib.h"

cBITMAP::cBITMAP()
{
	thepixels = 0;
	alphachannel = 0;
	pFileHeader = (BITMAP_FILEHEADER*) new char[sizeof(BITMAP_FILEHEADER)];
	pHeader = (BITMAP_HEADER*) new char[sizeof(BITMAP_HEADER)];
}

cBITMAP::~cBITMAP()
{
	delete pFileHeader;
	delete pHeader;
	if (thepixels) delete thepixels;
	if (alphachannel) delete alphachannel;
}

void cBITMAP::Load(const wchar_t* filename)
{
	fstream filestream;
	filestream.open(filename,ios::in | ios::binary);
	if (filestream.is_open())
	{
		if(!filestream.eof())
		{
			filestream.read((char*)pFileHeader,sizeof(BITMAP_FILEHEADER));
			if (pFileHeader->fType == 0x4D42) //bmp magic number
			{
				filestream.read((char*)pHeader,sizeof(BITMAP_HEADER));
				filestream.seekg(pFileHeader->OffBits);
				
				thepixels = new unsigned char[pHeader->SizeImage];
				
				int byte_per_pixel = pHeader->BitCount / 8;

				//read data and make up for the 4 byte data alignment
				if (byte_per_pixel!=4)
				{
					int offset = 4-((pHeader->Width*byte_per_pixel)%4);
					for (int i=0;i<pHeader->Height;i++)
					{
						filestream.read((char*)thepixels+(pHeader->Width*byte_per_pixel)*i,pHeader->Width*byte_per_pixel);
						filestream.seekg(offset,ios_base::cur);
					}
				}
				else //byte per pixel == 4!
				{
					unsigned char* thealphas = new unsigned char[pHeader->Height*pHeader->Width];
					alphachannel = new float[pHeader->Height*pHeader->Width];
					for (int i=0;i<pHeader->Height*pHeader->Width;i++)
						//for (int j=0;j<pHeader->Width;j++)
						{
							filestream.read((char*)thepixels+(i*3),3); //read COLOR (bgr)
							filestream.read((char*)thealphas+i,1); //read alpha
							alphachannel[i] = (float)thealphas[i]/255;
						}
					delete[] thealphas;
				}
			}

		}

	}
	filestream.close();


}

void cBITMAP::Render(int x, int y, BASE_RENDERER* pRenderer)
{
	if (alphachannel)
		BlitBitmapAlpha(x,y,pRenderer->framebuffer);
	else
		BlitBitmap(x,y,pRenderer->framebuffer);
}

void cBITMAP::BlitBitmap(int x, int y,FRAME_BUFFER* framebuffer)
{
	
	framebuffer->BlitMem(x,y,pHeader->Width,pHeader->Height,thepixels);

}

void cBITMAP::BlitBitmapAlpha(int posx, int posy,FRAME_BUFFER* framebuffer)
{
	if (alphachannel)
	{
		int w = pHeader->Width;
		int h = pHeader->Height;

		for (int inc_y=h-1;inc_y>=0;inc_y--)
			for (int inc_x=0;inc_x<w;inc_x++)
			{
				int x = inc_x + posx;
				int y = h-inc_y+posy;
				int index = (inc_y*w)+inc_x;
				framebuffer->PutPixelAlpha(	*(static_cast<COLOR*>(thepixels)+index),
					x,
					y,
					alphachannel[index]);

			}
	}
}